﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Iesi.Collections.Generic;
using Blazing.BusinessObjects.Widgets;
using System.Collections.Generic;

namespace Blazing.UI.Cms.Admin.Usercontrols
{
    public partial class EditPageWidgets : System.Web.UI.UserControl
    {
        private IList<Blazing.BusinessObjects.Widgets.PageWidget> viewStateItems
        {
            get
            {
                if (ViewState["viewStateItems"] == null)
                    return new List<Blazing.BusinessObjects.Widgets.PageWidget>();
                return ViewState["viewStateItems"] as IList<Blazing.BusinessObjects.Widgets.PageWidget>;
            }
            set
            {
                ViewState["viewStateItems"] = value;
            }
        }

        public IList<Blazing.BusinessObjects.Widgets.PageWidget> PageWidgets
        {
            get
            {
                UpdateRemovedItems();
                return viewStateItems;
            }
            set
            {
                for (int i = 1; i <= value.Count; i++)
                    value[0].ID = i;

                viewStateItems = value;
                RepeaterPageWidgets.DataSource = value;
                RepeaterPageWidgets.DataBind();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void LinkButtonAdd_Click(object sender, EventArgs e)
        {
            IList<Blazing.BusinessObjects.Widgets.PageWidget> items = PageWidgets;
            PageWidget w = SelectPageWidget2.PageWidget;
            w.ID = items.Count + 1;
            items.Add(w);
            PageWidgets = items;
        }

        private void UpdateRemovedItems()
        {
            IList<Blazing.BusinessObjects.Widgets.PageWidget> widgets = viewStateItems;
            foreach (RepeaterItem item in RepeaterPageWidgets.Items)
            {
                SelectPageWidget control = item.FindControl("SelectPageWidget1") as SelectPageWidget;
                if (control != null && control.PageWidget != null && !control.IsActive)
                {
                    foreach (PageWidget w in widgets)
                    {
                        if (w.ID == control.PageWidget.ID)
                        {
                            widgets.Remove(w);
                            break;
                        }
                    }
                }
            }
            viewStateItems = widgets;
        }
    }
}